package com.wwt.springboot_vue.controller;

import com.wwt.springboot_vue.bean.Category;
import com.wwt.springboot_vue.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("findAllCategory")
    public Map<String, Object> findAllCategory() {
        Map<String, Object> map = new HashMap<>();
        List<Category> list = categoryService.findAllCategory();
        System.out.println(categoryService.findAllCategory());
        map.put("all",list);
        return map;
    }
    @GetMapping("findAllCategoryBylimit")
    public Map<String, Object> findAllCategoryBylimit(int start,int size) {
        Map<String, Object> map = new HashMap<>();
        List<Category> list = categoryService.findAllCategoryBylimit(start, size);
        map.put("all",list);
        return map;
    }

    @PostMapping("add")
    public Map<String, Object> add(@RequestBody Category category) {
        Map<String, Object> map = new HashMap<>();
        System.out.println(category);
        try {
            categoryService.add(category);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
        }

        return map;
    }

    @PostMapping("update")
    public Map<String, Object> update(@RequestBody Category category) {
        Map<String, Object> map = new HashMap<>();
        System.out.println(category);
        try {
            categoryService.update(category);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
        }

        return map;
    }
    @GetMapping("delete")
    public Map<String,Object> deleteOne(int category_id){
        Map<String,Object> map = new HashMap<>();
        try{
            categoryService.delete(category_id);
            map.put("success",true);
        }catch (Exception e){
            map.put("success",false);
        }
        return map;
    }
    @GetMapping("getCategoryIdByName")
    public Map<String,Object> getCategoryIdByName(String category_name){
        Map<String,Object> map = new HashMap<>();
       Category category= categoryService.getCategoryIdByName(category_name);
        if(category != null){
            map.put("id",category);
            map.put("success",true);
        }else{
            map.put("success",false);
        }
        return map;
    }


    @GetMapping("count")
    public int count(){
        int i=categoryService.count();
        System.out.println(i);
        return i;
    }
}